<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="dom"
      style="margin-top: 0"
      action=""
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="false"
      :http-request="customRequest"
      accept=".doc,.docx,.pdf,.txt,.xlsx,.xls,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.bmp,.svg,.webp,.mp3,.wav,.ogg,.aac,.mp4,.avi,.mov,.wmv,.mkv,.zip,.rar,.7z,.tar,.gz,.wgt"
    >
      <el-button type="primary">点击上传</el-button>
      <div v-if="progress > 0 && progress < 100">上传进度: {{ progress }}%</div>
      <div
        v-if="uploadResult ? uploadResult : fileType.fileType"
        style="margin-left: 10px"
      >
        {{ uploadResult ? uploadResult : fileType.fileType }}
      </div>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { upload } from 'qiniu-js';
import { getQiniuUploadToken } from '@/api/upload';
defineProps({
  fileType: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(['fileList']);
const extension = ref('');
const progress = ref(0);
const uploadResult = ref(null);
const dom = ref(null);
const beforeUpload = (file) => {
  const parts = file.name.split('.');
  extension.value = '.' + parts.pop(); // 获取最后一部分并加上点
  // 可以在这里加入对文件格式和大小的验证
  return true; // 返回 true 表示继续上传
};

const customRequest = async ({ file, onSuccess, onError }) => {
  // 获取上传凭证
  const { data } = await getQiniuUploadToken({ fileType: extension.value });
  if (!data || !data.length || !data[0].token) {
    onError('未能获取有效的上传 Token');
    return;
  }

  const uploadToken = data[0].token;
  const key = data[0].key;
  // 创建上传实例
  const observable = upload(
    file,
    key,
    uploadToken // 上传 Token
  );

  // 订阅上传进度和结果
  observable.subscribe({
    next(res) {
      progress.value = Math.floor(res.total.percent); // percent 是从 0 到 1 的值
    },
    error(err) {
      console.error('上传错误:', err);
      onError(err);
    },
    complete(res) {
      progress.value = 100; // 完成后进度设为 100
      // uploadResult.value = JSON.parse(JSON.stringify(res)).key; // 保存结果
      onSuccess(res); // 调用成功回调
    },
  });
};

const handleSuccess = (response, file) => {
  console.log('file:', file.name);
  // 成功上传后的处理
  emit('fileList', { response, file });
  uploadResult.value = file.name;
};

const handleError = (err, file) => {
  // 上传失败后的处理
  console.error('上传失败:', err, file);
};
const clearList = () => {
  uploadResult.value = '';
};
// 暴露方法给父组件
defineExpose({
  clearList,
});
</script>

<style>
/* 可以添加相关样式 */
.upload-demo {
  margin-top: 20px;
}
:deep(.upload-demo) {
  margin-top: 0 !important;
}
</style>
